//
//  WmcEditPhoneVC.swift
//  YPWatermarkCamera
//
//  Created by 周诗松 on 2022/4/14.
//

import UIKit

// MARK: - 扩展WmcEditPhoneVC + WmcNavigatorProtocol

extension WmcEditPhoneVC: WmcNavigatorProtocol {
    static func navigationPaths() -> [WmcNavigatorManager.Path] {
        return [.editPhone]
    }

    static func willMakeNavigationVC(with parms: WmcNavigatorManager.Parms) -> UIViewController {
        
        var vm = WmcEditPhoneVM()
        
        if let viewModel = parms.context as? WmcEditPhoneVM {
            vm = viewModel
        }
        
        let vc = WmcEditPhoneVC(vm)
        return vc
    }
}

extension WmcEditPhoneVC: WmcVMProtocol {
    typealias VMType = WmcEditPhoneVM
}

// MARK: - [WmcEditPhoneVC]

class WmcEditPhoneVC: WmcBaseVC {
    // Lifecycle

    override func viewDidLoad() {
        super.viewDidLoad()

        title = "换绑手机号"
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        
        timerDispose?.dispose()
    }

    // Internal

    override func makeUI() {
        view.backgroundColor = .wmc_grayH20_F7F7F7
        makeNavView(showShadow: false)

        addSubview(tipLabel)
        addSubview(phoneLabel)
        addSubview(inputBgView)
        addSubview(submitBtn)

        inputBgView.addSubview(phoneTitleLabel)
        inputBgView.addSubview(phoneTextField)
        inputBgView.addSubview(line)
        inputBgView.addSubview(authCodeTitleLabel)
        inputBgView.addSubview(authCodeTextField)
        inputBgView.addSubview(authCodeBtn)

        tipLabel.snp.makeConstraints { make in
            make.top.equalTo(navView.snp.bottom).offset(13)
            make.height.equalTo(21)
            make.centerX.equalToSuperview()
        }

        phoneLabel.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(tipLabel.snp.bottom).offset(1)
            make.height.equalTo(27)
        }

        inputBgView.snp.makeConstraints { make in
            make.top.equalTo(phoneLabel.snp.bottom).offset(13)
            make.left.right.equalToSuperview()
            make.height.equalTo(114)
        }

        phoneTitleLabel.snp.makeConstraints { make in
            make.top.left.equalTo(16)
        }

        phoneTextField.snp.makeConstraints { make in
            make.centerY.equalTo(phoneTitleLabel)
            make.left.equalTo(125)
            make.right.equalTo(-20)
        }

        line.snp.makeConstraints { make in
            make.left.equalTo(17)
            make.right.equalTo(-17)
            make.height.equalTo(1)
            make.centerY.equalToSuperview()
        }

        authCodeTitleLabel.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.bottom.equalTo(-16)
        }

        authCodeTextField.snp.makeConstraints { make in
            make.centerY.equalTo(authCodeTitleLabel)
            make.left.equalTo(125)
            make.right.equalTo(authCodeBtn.snp.left).offset(-20)
        }

        authCodeBtn.snp.makeConstraints { make in
            make.right.equalTo(-16)
            make.centerY.equalTo(authCodeTitleLabel)
            make.width.equalTo(94)
            make.height.equalTo(36)
        }

        submitBtn.snp.makeConstraints { make in
            make.top.equalTo(inputBgView.snp.bottom).offset(45)
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.height.equalTo(50)
        }
    }

    override func bindViewModel() {}

    // Private

    private lazy var tipLabel: UILabel = {
        let label = UILabel()
        label.text = "您当前绑定的手机号码："
        label.font = 14.wmc_font
        label.textColor = .wmc_grayH13_ACAEAF
        label.textAlignment = .center
        return label
    }()

    private lazy var phoneLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 18, weight: .medium)
        label.textColor = .wmc_grayH2_323233
        label.textAlignment = .center
        label.text = WmcLoginManager.shared.wmcAccountModel?.phone
        return label
    }()

    private lazy var inputBgView: UIView = {
        let view = UIView()
        view.backgroundColor = .wmc_white_FFFFFF
        return view
    }()

    private lazy var phoneTitleLabel: UILabel = {
        let label = UILabel()
        label.text = "新手机号码"
        label.font = 17.wmc_font
        label.textColor = .wmc_grayH2_323233
        return label
    }()

    private lazy var authCodeTitleLabel: UILabel = {
        let label = UILabel()
        label.text = "验证码"
        label.font = 17.wmc_font
        label.textColor = .wmc_grayH2_323233
        return label
    }()

    private lazy var phoneTextField: UITextField = {
        let textField = UITextField()
        textField.placeholder = "请输入新的手机号码"
        textField.font = 17.wmc_font
        textField.textColor = .wmc_grayH2_323233
        textField.keyboardType = .numberPad
        textField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)
        return textField
    }()

    private lazy var authCodeTextField: UITextField = {
        let textField = UITextField()
        textField.placeholder = "请输入验证码"
        textField.font = 17.wmc_font
        textField.textColor = .wmc_grayH2_323233
        textField.keyboardType = .numberPad
        textField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)
        return textField
    }()

    private lazy var authCodeBtn: UIButton = {
        let btn = UIButton(type: .custom)
        let image = UIColor.wmc_mainTheme.yp.uiImage
        btn.setBackgroundImage(image, for: .normal)
        btn.setTitle("获取验证码", for: .normal)
        btn.setTitleColor(.wmc_white_FFFFFF, for: .normal)
        btn.titleLabel?.font = 16.wmc_font
        btn.layer.cornerRadius = 4
        btn.layer.masksToBounds = true
        btn.isEnabled = false
        btn.addTarget(self, action: #selector(onSendAuthCodeAction(_:)), for: .touchUpInside)
        return btn
    }()

    private lazy var line: UIView = {
        let view = UIView()
        view.backgroundColor = .wmc_grayH19_F5F5F5
        return view
    }()

    private lazy var submitBtn: UIButton = {
        let btn = UIButton(type: .custom)
        let image = UIColor.wmc_mainTheme.yp.uiImage
        btn.setBackgroundImage(image, for: .normal)
        btn.setTitle("确认", for: .normal)
        btn.setTitleColor(.wmc_white_FFFFFF, for: .normal)
        btn.titleLabel?.font = 18.wmc_font
        btn.layer.cornerRadius = 4
        btn.layer.masksToBounds = true
        btn.isEnabled = false
        btn.addTarget(self, action: #selector(onSubmitAction(_:)), for: .touchUpInside)
        return btn
    }()

    private var timerDispose: Disposable?

    @objc
    private func textFieldDidChange(_ sender: UITextField) {
        guard let text = sender.text else { return }

        if sender == phoneTextField {
            if text.count > 11 {
                let result = (text as NSString).substring(to: 11)
                sender.text = result
            }
        } else if sender == authCodeTextField {
            if text.count > 6 {
                let result = (text as NSString).substring(to: 6)
                sender.text = result
            }
        }

        
        let isValidPhone = phoneTextField.text?.count == 11
        let isAuthCode = authCodeTextField.text?.count ?? 0 > 3

        if seconds == defaultSeconds {
            authCodeBtn.isEnabled = isValidPhone
        }
        submitBtn.isEnabled = isValidPhone && isAuthCode
    }
    
//    func uptime() -> time_t {
//        var boottime = timeval()
//        var mib: [Int32] = [CTL_KERN, KERN_BOOTTIME]
////        var size = strideof(timeval)
//
//        var size = stride(ofValue: timeval)
//
//        var now = time_t()
//        var uptime: time_t = -1
//
//        time(&now)
//        if (sysctl(&mib, 2, &boottime, &size, nil, 0) != -1 && boottime.tv_sec != 0) {
//            uptime = now - boottime.tv_sec
//        }
//        return uptime
//    }
    
    private let defaultSeconds: Int = 60
    private lazy var seconds: Int = {
        return self.defaultSeconds
    }()
    
    private func startCountDown() {
        seconds = defaultSeconds
        timerDispose = Observable<Int>.interval(.seconds(1), scheduler: MainScheduler.instance).subscribe(onNext: { [weak self] num in
            guard let weakSelf = self else { return }
            weakSelf.seconds -= 1
            if weakSelf.seconds > 0 {
                let text = "\(weakSelf.seconds)s"
                weakSelf.authCodeBtn.setTitle(text, for: .normal)
                weakSelf.authCodeBtn.isEnabled = false
            } else {
                weakSelf.authCodeBtn.setTitle("获取验证码", for: .normal)
                weakSelf.authCodeBtn.isEnabled = true
                weakSelf.timerDispose?.dispose()
                weakSelf.seconds = weakSelf.defaultSeconds
            }
        })
    }

    @objc
    private func onSendAuthCodeAction(_ sender: UIButton) {
        view.endEditing(true)

        guard let newPhone = phoneTextField.text else { return }
        
        WmcHudManager.loading()
        viewModel.sendVerificationCode(phone: newPhone).subscribe { response in
            WmcHudManager.dismiss()
            self.startCountDown()
        } onError: { error in
            WmcHudManager.dismiss()
            WmcHudManager.toast(error)
        }.disposed(by: rx.disposeBag)
    }

    @objc
    private func onSubmitAction(_ sender: UIButton) {
        view.endEditing(true)
        
        guard let newPhone = phoneTextField.text, let authCode = authCodeTextField.text else { return }
        
        WmcHudManager.loading()
        viewModel.updatePhone(phone: newPhone, verificationCode: authCode).subscribe {[weak self] response in
            guard let weakSelf = self else { return }
            WmcHudManager.dismiss()
            WmcHudManager.toast("修改成功")
            WmcLoginManager.logout()
            weakSelf.tabBarController?.navigationController?.popViewController(animated: true)
            YPGCD.Delay(delay: 0.4) {
                weakSelf.checkLogin()
            }
        } onError: { error in
            WmcHudManager.dismiss()
            WmcHudManager.toast(error)
        }.disposed(by: rx.disposeBag)
    }
    
    private func checkLogin() -> Void {
    
        if !WmcLoginManager.shared.isLogin {
            if YPWmcManager.shared.isIndependentPage {
                WmcLoginManager.push(animated: true) {
                    WmcNavigatorManager.push(.myTeam)
                } failure: {
                    WmcHudManager.toast("登录失败")
                }
            } else {
                YPWmcManager.shared.delegate.loginDelegate?.loginNeed(.current, animated: true, success: {
                    WmcNavigatorManager.push(.myTeam)
                }, failure: {
                    WmcHudManager.toast("登录失败")
                })
            }
        }
    }
}
